package deibay.client.core;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.client.Command;
import deibay.client.Controller;
import deibay.messages.Message;

/**
 * @author  Joel Cordeiro
 */
public class MessageConsumer implements Runnable{

	private LinkedBlockingQueue<Message> receivedMessages = null;	
	private boolean keepAlive;
	private Controller controller;
	
	public MessageConsumer(Controller controller)
	{
		receivedMessages = new LinkedBlockingQueue<Message>();
		this.controller = controller;
		keepAlive = true;
	}

	public void run() {		
		while(keepAlive==true)
		{
			Message message;
			try {
				message = receivedMessages.take();
				Command c = Command.parse(message, controller);
				DeibayLogger.getInstance().getLog().log(Level.WARNING, "Processando mensagem: "+message.toString()+".\n");
				c.execute();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public synchronized void addReceivedMessage(Message message)
	{
		receivedMessages.offer(message);
	}
}
